import axios from 'axios'
import { Notification } from 'element-ui'
import store from '../store'
import Config from '@/config'

// 创建axios实例
const service = axios.create({
  baseURL: process.env.BASE_API, // api 的 base_url
  timeout: Config.timeout // 请求超时时间
})

// request拦截器
service.interceptors.request.use(
  config => {
    store.dispatch('LoadMask')
    config.headers['Content-Type'] = 'application/json'
    // 刷新token
    return config
  },
  error => {
    // Do something with request error
    console.log(error) // for debug
    Promise.reject(error)
  }
)

// response 拦截器
service.interceptors.response.use(
  response => {
    // 获取七牛云上传token成功后不必关闭菊花
    store.dispatch('CloseMask')
    const status = response.status
    if (status < 200 || status > 300) {
      Notification.error({
        title: response.message
      })
      return Promise.reject('error')
    } else {
      return response.data
    }
  },
  error => {
    console.log(error)
    store.dispatch('CloseMask')
    if (error.toString().indexOf('Error: timeout') !== -1) {
      Notification.error({
        title: '网络请求超时',
        duration: 2500
      })
      return Promise.reject(error)
    } else {
      Notification.error({
        title: '请求错误',
        duration: 2500
      })
      return Promise.reject(error)
    }
  }
)
export default service
